import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { userLoginUsingPOST } from '@/api/user'

export const useUserStore = defineStore('user', () => {
  const userInfo = ref(null)
  const token = ref(localStorage.getItem('token') || '')

  const isLoggedIn = computed(() => !!token.value)
  const isAdmin = computed(() => userInfo.value?.userRole === 'admin')

  const login = async (loginForm) => {
    try {
      const response = await userLoginUsingPOST(loginForm)
      console.log('登录响应:', response)
      
      // 检查响应结构
      if (response && response.data) {
        userInfo.value = response.data
        token.value = response.data.token || 'mock-token'
        localStorage.setItem('token', token.value)
        localStorage.setItem('userInfo', JSON.stringify(response.data))
        return { success: true }
      } else if (response && response.code === 0) {
        // 如果响应直接包含用户信息
        userInfo.value = response.data || response
        token.value = (response.data || response).token || 'mock-token'
        localStorage.setItem('token', token.value)
        localStorage.setItem('userInfo', JSON.stringify(response.data || response))
        return { success: true }
      } else {
        console.error('登录响应格式异常:', response)
        return { success: false, message: '登录响应格式异常' }
      }
    } catch (error) {
      console.error('登录错误:', error)
      return { success: false, message: error.message || '登录失败' }
    }
  }

  const logout = () => {
    userInfo.value = null
    token.value = ''
    localStorage.removeItem('token')
    localStorage.removeItem('userInfo')
  }

  const initUserInfo = () => {
    const savedUserInfo = localStorage.getItem('userInfo')
    if (savedUserInfo) {
      userInfo.value = JSON.parse(savedUserInfo)
    }
  }

  return {
    userInfo,
    token,
    isLoggedIn,
    isAdmin,
    login,
    logout,
    initUserInfo
  }
})
